package com.earthchen.demo.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
import com.earthchen.core.base.BaseController;
import com.earthchen.core.support.shiro.filter.ShiroFilterChainManager;
import com.earthchen.core.vo.ResultVO;
import com.earthchen.demo.domain.SysResource;
import com.earthchen.demo.domain.SysRole;
import com.earthchen.demo.domain.SysUser;
import com.earthchen.demo.dto.AuthorityRoleResourceDTO;
import com.earthchen.demo.dto.PageParamDTO;
import com.earthchen.demo.enums.ExceptionEnum;
import com.earthchen.demo.exception.AuthException;
import com.earthchen.demo.service.SysResourceService;
import com.earthchen.demo.service.SysRoleService;
import com.earthchen.demo.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author earthchen
 * @date 2018/9/6
 **/
@RequestMapping("/role")
@RestController
public class RoleController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysResourceService sysResourceService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private ShiroFilterChainManager shiroFilterChainManager;


    /**
     * 获取角色关联的(roleId)对应用户列表
     *
     * @param roleId
     * @param pageParamDTO
     * @return
     */
    @GetMapping("/user/{roleId}")
    public ResultVO getUserListByRoleId(@PathVariable long roleId, PageParamDTO pageParamDTO) {
        PageHelper.startPage(pageParamDTO.getPage(), pageParamDTO.getSize());
        List<SysUser> users = sysUserService.getUserListByRoleId(roleId);
        return ResultVO.success(wrapPageResult(users));
    }


    /**
     * 获取角色(roleId)所被授权的API资源
     *
     * @param roleId
     * @param pageParamDTO
     * @return
     */
    @GetMapping("/api/{roleId}")
    public ResultVO getRestApiExtendByRoleId(@PathVariable long roleId, PageParamDTO pageParamDTO) {
        PageHelper.startPage(pageParamDTO.getPage(), pageParamDTO.getSize());
        List<SysResource> sysResources = sysResourceService.getAuthorityApisByRoleId(roleId);
        return ResultVO.success(wrapPageResult(sysResources));
    }


    /**
     * 获取角色(roleId)所被授权的menu资源
     *
     * @param roleId
     * @param pageParamDTO
     * @return
     */
    @GetMapping("/menu/{roleId}")
    public ResultVO getMenusByRoleId(@PathVariable long roleId, PageParamDTO pageParamDTO) {
        PageHelper.startPage(pageParamDTO.getPage(), pageParamDTO.getSize());
        List<SysResource> sysResources = sysResourceService.getAuthorityMenusByRoleId(roleId);
        return ResultVO.success(wrapPageResult(sysResources));
    }


    /**
     * 授权资源给角色
     *
     * @param authorityRoleResourceDTO
     * @return
     */
    @PostMapping("/authority/resource")
    public ResultVO authorityRoleResource(AuthorityRoleResourceDTO authorityRoleResourceDTO) {
        sysRoleService.authorityRoleResource(authorityRoleResourceDTO.getRoleId(), authorityRoleResourceDTO.getResourceId());
        shiroFilterChainManager.reloadFilterChain();
        return ResultVO.success();
    }


    /**
     * 删除对应的角色的授权资源
     *
     * @param roleId
     * @param resourceId
     * @return
     */
    @DeleteMapping("/authority/resource/{roleId}/{resourceId}")
    public ResultVO deleteAuthorityRoleResource(@PathVariable Long roleId, @PathVariable Long resourceId) {
        sysRoleService.deleteAuthorityRoleResource(roleId, resourceId);
        shiroFilterChainManager.reloadFilterChain();
        return SUCCESS;
    }

    /**
     * 获取角色LIST
     *
     * @param pageParamDTO
     * @return
     */
    @GetMapping("/list")
    public ResultVO getRoles(PageParamDTO pageParamDTO) {
        Page<SysRole> page = new Page<>(pageParamDTO.getPage(), pageParamDTO.getSize());
        Page<SysRole> roles = sysRoleService.selectPage(page);
        return ResultVO.success(roles);
    }

    /**
     * 添加角色
     *
     * @param role
     * @return
     */
    @PostMapping("")
    public ResultVO addRole(@RequestBody SysRole role) {
        boolean flag = sysRoleService.insert(role);
        if (!flag) {
            throw new AuthException(ExceptionEnum.SAVE_ROLE_ERROR);
        }
        return SUCCESS;
    }

    /**
     * 更新角色
     *
     * @param role
     * @return
     */
    @PutMapping("")
    public ResultVO updateRole(@RequestBody SysRole role) {
        boolean flag = sysRoleService.update(role, new EntityWrapper<SysRole>()
                .where("role_id={0}", role.getId()));
        if (!flag) {
            throw new AuthException(ExceptionEnum.SAVE_ROLE_ERROR);
        }
        return SUCCESS;
    }

    /**
     * 根据角色ID删除角色
     *
     * @param roleId
     * @return
     */
    @DeleteMapping("{roleId}")
    public ResultVO deleteRoleByRoleId(@PathVariable Long roleId) {
        boolean flag = sysRoleService.deleteById(roleId);
        if (!flag) {
            throw new AuthException(ExceptionEnum.DELETE_ROLE_ERROR);
        }
        return SUCCESS;
    }


    //    /**
//     * 获取角色未关联的用户列表
//     * @param roleId
//     * @param currentPage
//     * @param pageSize
//     * @return
//     */
//    @GetMapping("user/-/{roleId}/{currentPage}/{pageSize}")
//    public Message getUserListExtendByRoleId(@PathVariable Integer roleId, @PathVariable Integer currentPage, @PathVariable Integer pageSize) {
//        PageHelper.startPage(currentPage, pageSize);
//        List<AuthUser> users = userService.getNotAuthorityUserListByRoleId(roleId);
//        users.forEach(user -> user.setPassword(null));
//        PageInfo pageInfo = new PageInfo(users);
//        return new Message().ok(6666, "return users success").addData("data", pageInfo);
//    }

//
//    @SuppressWarnings("unchecked")
//    @ApiOperation(value = "获取角色(roleId)未被授权的API资源")
//    @GetMapping("api/-/{roleId}/{currentPage}/{pageSize}")
//    public Message getRestApiByRoleId(@PathVariable Integer roleId, @PathVariable Integer currentPage, @PathVariable Integer pageSize) {
//        PageHelper.startPage(currentPage, pageSize);
//        List<AuthResource> authResources = resourceService.getNotAuthorityApisByRoleId(roleId);
//        PageInfo pageInfo = new PageInfo(authResources);
//        return new Message().ok(6666, "return api success").addData("data", pageInfo);
//    }
//

//
//    @SuppressWarnings("unchecked")
//    @ApiOperation(value = "获取角色(roleId)未被授权的menu资源")
//    @GetMapping("menu/-/{roleId}/{currentPage}/{pageSize}")
//    public Message getMenusExtendByRoleId(@PathVariable Integer roleId, @PathVariable Integer currentPage, @PathVariable Integer pageSize) {
//        PageHelper.startPage(currentPage, pageSize);
//        List<AuthResource> authResources = resourceService.getNotAuthorityMenusByRoleId(roleId);
//        PageInfo pageInfo = new PageInfo(authResources);
//        return new Message().ok(6666, "return api success").addData("data", pageInfo);
//    }
//


}
